<?php

namespace App\Admin\Controllers;

use App\Models\Product;
use App\Models\ProductClass;
use App\Models\ProductSku;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Collection;

class ProductController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品管理';
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Product());

        $grid->quickSearch('title');

        $grid->column('id', 'Id');
        $grid->image('商品图片')->lightbox(['zooming' => true,'height'=>'70']);
        $grid->column('title', '标题')->width(200);
        $grid->column('category_id','所属分类')->display(function ($categoryId) {
           return ProductClass::find($categoryId)->title;
        });
        $grid->column('sales', '销量');
        $grid->column('price', '价格');
        $states = [
            'on'  => ['value' => 1, 'text' => '上架', 'color' => 'primary'],
            'off' => ['value' => 0, 'text' => '下架', 'color' => 'default'],
        ];
        $grid->column('on_sale','是否上架')->switch($states)->filter([
            1=>'上架',
            2=>'下架'
        ]);
        $grid->column('created_at', '上架时间');

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();

            $filter->column(1/2,function ($filter) {
                $filter->like('title','商品名称');
            });
            $filter->column(1/2,function ($filter) {
                $options=collect(ProductClass::selectOptions());
                $options->pull(0);
                $filter->equal('category_id', '所属分类')
                    ->select($options);
            });

        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Product::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('title', __('Title'));
        $show->field('image', __('Image'));
        $show->field('introduction', __('Introduction'));
        $show->field('sales', __('Sales'));
        $show->field('price', __('Price'));
        $show->field('details', __('Details'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Product());

        $form->text('title', '商品名称')->rules('required');
        $options = collect(ProductClass::selectOptions());
        $options->pull(0);
        $form->select('category_id', '所属分类')->options($options)->rules('required');
        $form->image('image', '商品图片')->rules('required');
        $form->text('introduction', '商品简介')->rules('required');

        $states = [
            'on' => ['value' => 1, 'text' => '出售', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '不出售', 'color' => 'danger'],
        ];
        $form->currency('price', '展示价格')->symbol('￥')->required();
        $form->switch('on_sale', '是否出售')->states($states);
        $form->editor('details', '商品详情')->rules('required');
        //编辑设置默认值
        if ($form->isEditing()) {
            $product=Product::find(request()->route('product'));
            $form->sku('skus', '商品sku')->default($this->applySkuData($product->skus));
        }else {
            $form->sku('skus', '商品sku');
        }

        //忽略sku保存
        $form->ignore('skus');
        $form->saved(function (Form $form) {
            $requestSku = json_decode(request('skus'), true);
            //如果是更新的话删除sku重新填充
            if (request()->isMethod('PUT')) {
                $form->model()->skus()->delete();
            }
            $sku = [];
            foreach ($requestSku['sku'] as $item) {
                $sku[] = [
                    'attrs' => json_encode($requestSku['attrs'], JSON_UNESCAPED_SLASHES),
                    'sku' => collect($item)->intersectByKeys(['price', 'item'])->toJson(),
                    'price' => $item['price'],
                    'stock' => $item['stock'],
                ];
            }
            //循环存入
            $form->model()->skus()->createMany($sku);
        });
        return $form;
    }

    /**
     * 将数据转换为json
     * @param $sku Collection
     */
    protected  function  applySkuData($sku) {;
        $data=[
            'type'=>$sku->first()->type,
            'attrs'=>json_decode($sku->first()->attrs,true)
        ];
        //将sku信息批量添加
        $sku->each(function ($item) use(&$data){
            $itemData=json_decode($item->sku,true);
            $itemData['price']=$item->price;
            $itemData['stock']=$item->stock;
            $itemData['id']=$item->id;
            $data['sku'][]=$itemData;
        });

        return json_encode($data,JSON_UNESCAPED_SLASHES);
    }
}
